import 'package:dio/dio.dart';
import 'package:wanandroid/common/user_info_model.dart';

import 'logger.dart';

class HttpManager {
  Dio? _dio;

  static final HttpManager _instance = HttpManager._internal();

  factory HttpManager() => _instance;

  HttpManager._internal() {

    Map<String, String> headerMap = {};
    List<String>? cookies = User().cookie;
    headerMap["Cookie"] = cookies.toString();

    BaseOptions options = BaseOptions(
      //baseUrl: 'https://api.example.com',
        connectTimeout: const Duration(seconds: 10),
        receiveTimeout: const Duration(seconds: 15),
        headers: headerMap
    );
    _dio = Dio(options);

    // 添加拦截器
    _dio?.interceptors.add(InterceptorsWrapper(
      onRequest: (options, handler) {
        return handler.next(options);
      },
      onResponse: (response, handler) {
        // 在这里统一处理响应
        return handler.next(response); // continue
      },
      onError: (DioError e, handler) {
        // 在这里统一处理错误
        return handler.next(e); //continue
      },
    ));
  }

  // GET 请求
  Future get(String url, {Map<String, dynamic>? params}) async {
    try {
      Response? response = await _dio?.get(url, queryParameters: params);
      return response;
    } on DioError catch (e) {
      _handleError(e);
      return null;
    }
  }

  // POST 请求
  Future post(String url, FormData data) async {
    try {
      Response? response = await _dio?.post(url, data: data);
      return response;
    } on DioError catch (e) {
      _handleError(e);
      return null;
    }
  }

  // 处理错误
  void _handleError(DioException error) {
    switch (error.type) {
      case DioExceptionType.connectionTimeout:
        logger.e("Connection Timeout Exception");
        break;
      case DioExceptionType.sendTimeout:
        logger.e("Send Timeout Exception");
        break;
      case DioExceptionType.receiveTimeout:
        logger.e("Receive Timeout Exception");
        break;
      case DioExceptionType.badCertificate:
        logger.e("Bad Certificate Exception");
        break;
      case DioExceptionType.badResponse:
        logger.e("Received invalid status code: ${error.response?.statusCode}");
        break;
      case DioExceptionType.cancel:
        logger.e("Request to API server was cancelled");
        break;
      case DioExceptionType.connectionError:
        logger.e("Connection Error Exception");
        break;
      case DioExceptionType.unknown:
        logger.e("Unexpected error: ${error.message}");
        break;
    }
  }
}
